/**
 * 
 */
package fhq.hcmute.edu.vn.network;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.Window;
import fhq.hcmute.edu.vn.activities.R;
import fhq.hcmute.edu.vn.message.MyMessage;

/**
 * @author Hien Nguyen Nov 2, 2012
 */
public class SendAndReceive extends AsyncTask<MyMessage, Void, Void> {
	private ProgressDialog progressDialog;
	private Activity activity;
	private Handler handler;
	private int what = 0;

	public SendAndReceive(Activity activity, int what, Handler handler) {
		this.activity = activity;
		this.handler = handler;
		this.what = what;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		progressDialog.dismiss();
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = new ProgressDialog(activity);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progressDialog.setMessage(activity.getResources().getString(
				R.string.Dialog_Message_Please_Wait));
		progressDialog.show();
	}

	@Override
	protected Void doInBackground(MyMessage... params) {
		Network network = Network.getInstance();
		if (network.isConnected()) {
			try {
				MyMessage message = params[0];
				network.sendToServer(message);
				message = network.receiveFromServer();
				handler.sendMessage(handler.obtainMessage(what,
						message));
			} catch (IOException e) {
				handler.sendMessage(handler.obtainMessage(what,
						null));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
